﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "GbmpDrawStraightModelLineCmd.h"
#include "GbmpUiPlatformCommandRegister.h"
#include "GbmpUiPlatformCommandIds.h"
#include "CmdStatusUtils.h"
#include "ActionDrawStraightElementInput.h"
#include "ActionDrawStraightElementCreator.h"
#include "GbmpSnapEndPointPriorityTypesPreprocessor.h"
#include "AddGbmpDynamicPannelUtils.h"
#include "GbmpControlIds.h"
#include "IUserTransaction.h"
#include "IModelView.h"
#include "GbmpUiPlatformUtils.h"
#include "IModelLine.h"
#include "ILine2d.h"
#include "IElementBasicInformation.h"
#include "IJournalCheckData.h"
#include "JournalUtils.h"
#include "UiDocumentViewUtils.h"
#include "IElementJoin.h"
#include "ISnap.h"
#include "IGraphicsNodeReference.h"
#include "IElementJoinBehavior.h"
#include "IGenericElement.h"
#include "ICombinedSnap.h"
#include "IGraphicsPlane.h"
#include "ILine3d.h"
#include "DebugMode.h"
#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gcmp;

EXPOSE_DEBUG_MODE_EXPORT(TransientWorkPlane, GCMP_COMMON_DRAW_EXPORT);
EXPOSE_DEBUG_MODE_EXPORT(Snap3DAxialDirectionLine, GCMP_COMMAND_ACTION_EXPORT);
EXPOSE_DEBUG_MODE_EXPORT(OpenSnap3DParallel, GCMP_COMMAND_ACTION_EXPORT);

bool GbmpDrawStraightModelLineCmd::AddJoin4ModelLines(IDocument* pDoc, IModelLine* pAttachingModelLine, JoinPosition attachingPos, IModelLine* pAttachedModelLine, JoinPosition attachedPos)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDoc, L"无效pDoc",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pAttachingModelLine, L"无效pAttachingModelLine",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pAttachedModelLine, L"无效pAttachedModelLine",L"GDMPLab",L"2024-03-30");
    gcmp::JoinData joinData(pAttachingModelLine->GetOwnerElement()->GetElementId(), attachingPos, pAttachedModelLine->GetOwnerElement()->GetElementId(), attachedPos);
    IElementJoin::Create(gcmp::IElementJoinBehavior::CreateElementJoinNullBehavior(pDoc), joinData);
    return true;
}

bool GbmpDrawStraightModelLineCmd::CreateModelLineJoinsBySnap(gcmp::IDocument* pDoc, IModelLine* pModelLine, JoinPosition joinPosition, const ISnap* pSnap)
{
    DBG_WARN_AND_RETURN_UNLESS(nullptr != pDoc, false, L"pDoc为空",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_UNLESS(nullptr != pSnap, false, L"pSnap为空",L"GDMPLab",L"2024-03-30");

    const ICombinedSnap* pCombineSnap = dynamic_cast<const ICombinedSnap*>(pSnap);
    if (pCombineSnap != nullptr && pCombineSnap->GetSubSnaps().size() > 0)
    {
        const std::vector<const ISnap*>& subSnaps = pCombineSnap->GetSubSnaps();
        FOR_EACH(subSnap, subSnaps)
        {
            CreateModelLineJoinsBySnap(pDoc, pModelLine, joinPosition, subSnap);
        }
        return true;
    }
    SnapType snapType = pSnap->GetSnapType();
    JoinPosition attachedPos;
    if (SnapType::StartPoint == snapType)
    {
        attachedPos = JoinPosition::Start;
    }
    else if (SnapType::EndPoint == snapType)
    {
        attachedPos = JoinPosition::End;
    }

    //添加捕捉约束
    switch (snapType)
    {
    case SnapType::StartPoint:
    case SnapType::EndPoint:
    {
        const IGraphicsNodeReference& nodeReference = **pSnap->GetSnappedGraphicsNodeReferences().begin();
        ElementId snapElementId = nodeReference.GetElementId();
        IGenericElement* snapElement = dynamic_cast<gcmp::IGenericElement*>(pDoc->GetElement(snapElementId));
        if (snapElement) {
            gcmp::IModelLine* pSnapedModelLine = dynamic_cast<gcmp::IModelLine*>(snapElement->GetExternalObject());
            if (pSnapedModelLine)
            {
                bool IsStraightLine = pSnapedModelLine->IsStraightLine();
                if (IsStraightLine)
                {
                    return AddJoin4ModelLines(pDoc, pModelLine, joinPosition, pSnapedModelLine, attachedPos);
                }
            }
        }
    }
    break;
    default:
        break;
    }

    return false;
}

REGISTER_GM_COMMAND(GbmpDrawStraightModelLineCmd)

GbmpDrawStraightModelLineCmd::GbmpDrawStraightModelLineCmd()
    : GbmpCommandBase(ID_CMD_GBMP_DRAW_STRAIGHT_MODEL_LINE)
{
}

GbmpDrawStraightModelLineCmd::~GbmpDrawStraightModelLineCmd()
{
}

bool GbmpDrawStraightModelLineCmd::IsVisible() const
{
    CMD_ONLY_VISIBLE_IN_PROJECT_ENVIRONMENT
}

bool GbmpDrawStraightModelLineCmd::IsEnabled() const
{
    CMD_ONLY_ENABLE_IN_PROJECT_ENVIRONMENT
}

OwnerPtr<IAction> GbmpDrawStraightModelLineCmd::ExecuteCommand(const gcmp::CommandParameters& cmdParams)
{
    ActionDrawStraightElementInput actionInput;
    actionInput.CommandId = GetCommandId();
    actionInput.DrawLineMode = DrawLineMode::Chained;
    actionInput.LineFinishedCallback = actionInput.CreateOnLineFinishedCallback(&GbmpDrawStraightModelLineCmd::OnLineFinished, this);

    std::vector<Int64> priorityTypes;
    priorityTypes.emplace_back(typeid(IModelLine).hash_code());
    actionInput.SnapCandidatesPreprocessor = NEW_AS_OWNER_PTR(GbmpSnapEndPointPriorityTypesPreprocessor, priorityTypes);

    OwnerPtr<IAction> opAction = ActionDrawStraightElementCreator::Create(actionInput);

    // 开启动态上下文面板
    AddGbmpDynamicPannelUtils::SetupModelLineCreationContext(opAction.get(), ID_PAGE_GBMP_MODIFY);

    return TransferOwnership(opAction);
}

ElementId GbmpDrawStraightModelLineCmd::OnLineFinished(gcmp::IUiView* pCurrentView, const gcmp::Vector3d& startPt, const gcmp::Vector3d& endPt,
    const gcmp::ISnap* pStartSnap, const gcmp::ISnap* pEndSnap)
{
    DBG_WARN_AND_RETURN_UNLESS(pCurrentView, ElementId::InvalidID, L"pCurrentView为空",L"GDMPLab",L"2024-03-30");

    IDocument* pDoc = UiDocumentViewUtils::GetCurrentDocument();
    DBG_WARN_AND_RETURN_UNLESS(pDoc, ElementId::InvalidID, L"pDoc为空",L"GDMPLab",L"2024-03-30");

    IModelView* pModelView = UiDocumentViewUtils::GetCurrentModelView();
    DBG_WARN_AND_RETURN_UNLESS(pModelView, ElementId::InvalidID, L"pModelView为空",L"GDMPLab",L"2024-03-30");

    OwnerPtr<IUserTransaction> opTransaction = IUserTransaction::Create(pDoc, GBMP_TR(L"绘制直线模型线"));
    DBG_WARN_AND_RETURN_UNLESS(opTransaction.get(), ElementId::InvalidID, L"opTransaction为空",L"GDMPLab",L"2024-03-30");

    // 将三维坐标点转化为平面上的二维点
    ElementId planeId = pModelView->GetWorkPlaneId();
    DBG_WARN_AND_RETURN_UNLESS(planeId.IsValid(), ElementId::InvalidID, L"planeId无效",L"GDMPLab",L"2024-03-30");
    Coordinate3d planeCoord = GbmpUiPlatformUtils::GetPlaneCoordinate3d(pDoc, planeId);
    Vector2d startPtLocal = planeCoord.GetLocalPointXY(startPt);
    Vector2d endPtLocal = planeCoord.GetLocalPointXY(endPt);
    
    IModelLine* pModelLine;
    if (DEBUG_MODE(TransientWorkPlane) || DEBUG_MODE(Snap3DAxialDirectionLine) || DEBUG_MODE(OpenSnap3DParallel))
    {
        OwnerPtr<ILine3d> opCurve3d = ILine3d::Create(startPt, endPt);
        pModelLine = IModelLine::Create(pDoc, TransferOwnership(opCurve3d), ElementCreationOptions::Normal);
        DBG_WARN_AND_RETURN_UNLESS(pModelLine, ElementId::InvalidID, L"创建ModelLine失败",L"GDMPLab",L"2024-03-30");
    }
    else
    {
        OwnerPtr<ILine2d> opCurve = ILine2d::Create(startPtLocal, endPtLocal);
        pModelLine = IModelLine::Create(pDoc, planeId, TransferOwnership(opCurve), ElementCreationOptions::Normal);
        DBG_WARN_AND_RETURN_UNLESS(pModelLine, ElementId::InvalidID, L"创建ModelLine失败",L"GDMPLab",L"2024-03-30");
    }

    // 记录检查点数据，用于日志回放比较
    OwnerPtr<IJournalCheckData> opXResultData = IJournalCheckData::Create();
    DBG_WARN_AND_RETURN_UNLESS(opXResultData, ElementId::InvalidID, L"opXResultData为空",L"GDMPLab",L"2024-03-30");
    opXResultData->SetName(L"X");
    opXResultData->SetData(startPt.X());
    JournalUtils::LogOrCompareCheckData(TransferOwnership(opXResultData));

    OwnerPtr<IJournalCheckData> opYResultData = IJournalCheckData::Create();
    DBG_WARN_AND_RETURN_UNLESS(opYResultData, ElementId::InvalidID, L"opYResultData为空",L"GDMPLab",L"2024-03-30");
    opYResultData->SetName(L"Y");
    opYResultData->SetData(startPt.Y());
    JournalUtils::LogOrCompareCheckData(TransferOwnership(opYResultData));

    OwnerPtr<IJournalCheckData> opZResultData = IJournalCheckData::Create();
    DBG_WARN_AND_RETURN_UNLESS(opZResultData, ElementId::InvalidID, L"opZResultData为空",L"GDMPLab",L"2024-03-30");
    opZResultData->SetName(L"Z");
    opZResultData->SetData(startPt.Z());
    JournalUtils::LogOrCompareCheckData(TransferOwnership(opZResultData));

    ElementId modelLineId = pModelLine->GetOwnerElement()->GetBasicInformation()->GetElementId();
    DBG_WARN_AND_RETURN_UNLESS(modelLineId.IsValid(), ElementId::InvalidID, L"modelLineId无效",L"GDMPLab",L"2024-03-30");

    if (pStartSnap)
    {
        CreateModelLineJoinsBySnap(pDoc, pModelLine, JoinPosition::Start, pStartSnap);
    }
    if (pEndSnap)
    {
        CreateModelLineJoinsBySnap(pDoc, pModelLine, JoinPosition::End, pEndSnap);
    }

    opTransaction->Commit();

    return modelLineId;
}
